package com.alibaba.nacos.naming.push.v2.task;

import com.alibaba.nacos.common.task.AbstractDelayTask;
import com.alibaba.nacos.common.task.NacosTask;
import com.alibaba.nacos.common.task.NacosTaskProcessor;
import com.alibaba.nacos.common.task.engine.NacosDelayTaskExecuteEngine;
import com.alibaba.nacos.common.task.engine.NacosExecuteTaskExecuteEngine;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class PushDelayTaskExecuteEngine
        extends NacosDelayTaskExecuteEngine {

    @Resource(name = "nacosExecuteTaskExecuteEngine")
    private NacosExecuteTaskExecuteEngine nacosExecuteTaskExecuteEngine;

    @PostConstruct
    void init() {
        setDefaultTaskProcessor(new PushDelayTaskProcessor());
    }

    @Override
    public void addTask(Object key,
                        AbstractDelayTask task) {
        super.addTask(key, task);
    }

    private class PushDelayTaskProcessor
            implements NacosTaskProcessor {

        @Override
        public boolean process(NacosTask task) {
            PushDelayTask pushDelayTask = (PushDelayTask) task;
            Service service = pushDelayTask.getService();
            PushExecuteTask pushExecuteTask = pushExecuteTask(service, pushDelayTask);
            // todo
//            pushExecuteTask.run();
            nacosExecuteTaskExecuteEngine.addTask(service, pushExecuteTask);
            return true;
        }
    }

    @Lookup
    public PushExecuteTask pushExecuteTask(Service service,
                                           PushDelayTask pushDelayTask) {
        throw new RuntimeException("never entry this");
    }
}
